<template>
  <div class="spare-picker">
    <!-- 统一选择：从备件库选择（含普通/特殊） -->
    <el-form-item label="从备件库选择">
      <el-select
        v-model="pickedIds"
        multiple
        filterable
        clearable
        collapse-tags
        collapse-tags-tooltip
        placeholder="选择需要的备件（可多选，含普通与特殊）"
        style="width: 100%"
        @change="syncPickedToRows"
      >
        <el-option
          v-for="op in allOptions"
          :key="op.value"
          :label="`(${typeLabel(op.type)}) ${op.label}`"
          :value="op.value"
        />
      </el-select>
    </el-form-item>

    <div class="toolbar">
      <el-button type="primary" plain @click="addManualRow">手动新增一行</el-button>
      <el-text type="info">编码仅允许 A-Z / 0-9 / - / _；手动新增如不存在将以 code 新建。</el-text>
    </div>

    <el-table
      :data="rows"
      border
      stripe
      size="small"
      :height="tableHeight"
       
      empty-text="请通过上方选择已有备件或点击手动新增"
    >
    <el-table-column label="备件名称" min-width="160">
  <template #default="{ row }">
    <el-input v-model="row.name" placeholder="请输入备件名称" @change="emitRows"/>
  </template>
</el-table-column>

<el-table-column label="编码" min-width="120">
  <template #default="{ row }">
    <el-input
      v-model="row.code"
      maxlength="64"
      placeholder="仅字母/数字/-/_"
      @input="row.code = sanitizeCode(row.code)"
      @change="emitRows"
    />
  </template>
</el-table-column>

<!-- 备件类型：库内行禁用，手动新增行可选 -->
<el-table-column label="备件类型" width="120" align="center">
  <template #default="{ row }">
    <el-select v-model="row.type" style="width:100%" :disabled="isLibRow(row)">
      <el-option :value="0" label="普通"/>
      <el-option :value="1" label="特殊"/>
    </el-select>
  </template>
</el-table-column>

<el-table-column label="数量" width="120" align="center">
  <template #default="{ row }">
    <el-input-number
      v-model="row.qty"
      :min="1" :step="1" controls-position="right"
      @change="emitRows"
    />
  </template>
</el-table-column>

<el-table-column label="采购周期(天)" width="140" align="center">
  <template #default="{ row }">
    <el-input-number
      v-model="row.orderDate"
      :min="0" :step="1" controls-position="right"
      @change="emitRows"
    />
  </template>
</el-table-column>


      <el-table-column label="操作" width="120" align="center" fixed="right">
        <template #default="{ $index }">
          <el-button link type="primary" size="small" @click="copyRow($index)">复制</el-button>
          <el-button link type="danger" size="small" @click="removeRow($index)">移除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { listSpare } from '@/api/sbtz/spare'

const props = defineProps({
  // 兼容父组件现有写法：仍然用 v-model:specialItems 传入/传出
  specialItems: { type: Array, default: () => [] },
  tableHeight: { type: [Number, String], default: 200 },
})
const emit = defineEmits(['update:specialItems'])

const allOptions = ref([]) // 全部（含普通/特殊）
const pickedIds = ref([])  // 下拉已选 id 列表
const rows = ref([])       // 真正编辑/提交的数据行（统一结构）

const typeLabel = (t) => (Number(t) === 1 ? '特殊' : '普通')
const sanitizeCode = (s='') => s.toUpperCase().replace(/[^A-Z0-9\-_]/g, '')
const isLibRow = (row) => !!row?.spareId;   // 有 spareId 就是从备件库选择的，禁用类型选择
const emitRows = () => emit('update:specialItems', rows.value);

// 初始化
onMounted(async () => {
  const res = await listSpare({ pageNum: 1, pageSize: 9999 })
  const list = res?.rows ?? res?.data ?? []
  allOptions.value = list.map(r => ({
    value: r.id,
    label: r.name,
    code: (r.code || '').toUpperCase(),
    type: Number(r.type) || 0,
    orderDate: Number(r.order_date ?? r.orderDate ?? 0),
  }))

  // 父传入回显（兼容编辑）
  if (Array.isArray(props.specialItems) && props.specialItems.length) {
    rows.value = props.specialItems.map(x => ({
      code: sanitizeCode(x.code),
      name: x.name || '',
      type: Number(x.type) || 0,
      qty: Number(x.qty) || 1,
      orderDate: Number(x.orderDate || 0),
      spareId: x.spareId, // 可能为空
    }))
    // 如果这些有 spareId，可把 pickedIds 带上（便于展示）
    pickedIds.value = rows.value.filter(r => r.spareId).map(r => r.spareId)
  }
})

// 父 prop 更新时同步（保持双向）
watch(
  () => props.specialItems,
  (v) => {
    if (Array.isArray(v)) {
      rows.value = v.map(x => ({
        code: sanitizeCode(x.code),
        name: x.name || '',
        type: Number(x.type) || 0,
        qty: Number(x.qty) || 1,
        orderDate: Number(x.orderDate || 0),
        spareId: x.spareId,
      }))
      pickedIds.value = rows.value.filter(r => r.spareId).map(r => r.spareId)
    }
  },
  { deep: true }
)

function syncPickedToRows() {
  const picked = new Set(pickedIds.value)
  rows.value = rows.value.filter(r => !r.spareId || picked.has(r.spareId))
  for (const id of picked) {
    if (!rows.value.some(r => r.spareId === id)) {
      const op = allOptions.value.find(x => x.value === id)
      if (op) {
        rows.value.push({
          spareId: id,
          code: op.code,
          name: op.label,
          type: Number(op.type) || 0,   // ← 库里的类型
          qty: 1,
          orderDate: Number(op.orderDate || 0),
        })
      }
    }
  }
  emitRows()
}


function addManualRow() {
  rows.value.push({ code: '', name: '', type: 1, qty: 1, orderDate: 0 })
  emitRows()
}

function copyRow(i) {
  const src = rows.value[i]
  const dup = JSON.parse(JSON.stringify(src))

  if (isLibRow(src)) {
    // ✅ 源是库内行：复制后仍是库内行（带 spareId），类型列继续禁用
    dup.spareId = src.spareId
  } else {
    // ✅ 源是手动行：复制后仍是手动行（不带 spareId），类型可编辑
    dup.spareId = undefined
  }

  rows.value.splice(i + 1, 0, dup)
  emitRows()
}


function removeRow(i) {
  const removed = rows.value[i]
  rows.value.splice(i, 1)
  if (removed?.spareId) {
    pickedIds.value = pickedIds.value.filter(id => id !== removed.spareId)
  }
  emit('update:specialItems', rows.value)
}
</script>

<style scoped>
.toolbar{ display:flex; align-items:center; gap:10px; margin-bottom:8px; }
</style>
